// src/logical/auth/auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AccountService } from 'src/logical/account/service/account.service';
import { BaseResultModel } from 'src/logical/common/models/BaseResult.model';
import { BaseService } from 'src/logical/common/services/base.service';
import { LoginLogEntity } from 'src/logical/login-log/entity/loginLog.entity';
import { LoginLogService } from 'src/logical/login-log/service/login-log.service';
import { RpOrgEntity } from 'src/logical/org/entity/org.entity';
import { jwtConstants } from '../constants';
import { loginAccountModel } from '../models/loginAccount.model';
import { TokenModel } from '../models/token.model';
import { TokenInfoModel } from '../models/tokenInfo.model';

@Injectable()
export class AuthService extends BaseService {
  constructor(
    private readonly accountService: AccountService,
    private readonly loginLogService: LoginLogService,
    private readonly jwtService: JwtService,
  ) {
    super();
  }

  async loginByAccount(body: loginAccountModel): Promise<BaseResultModel<any>> {
    const user = await this.accountService.findByAccount(body.account);
    const loginLogEntity: LoginLogEntity = new LoginLogEntity();
    loginLogEntity.id = this.nextId();
    if (user) {
      loginLogEntity.userId = user.id;
      loginLogEntity.account = user.account;
      loginLogEntity.userName = user.username;
      loginLogEntity.loginTime = this.getNowDate();
      console.log(loginLogEntity.getDataValue('loginTime'));

      if (user.passwd === body.passwd) {
        const tokenInfoModel: TokenInfoModel = new TokenInfoModel();

        tokenInfoModel.accountId = user.id;
        tokenInfoModel.account = user.account;
        tokenInfoModel.username = user.username;
        tokenInfoModel.orgId = user.orgId;
        tokenInfoModel.level = user.level;

        let orgName = '',
          orgType = '';
        if (user.orgId) {
          const org: RpOrgEntity = await RpOrgEntity.findByPk(user.orgId);
          if (org) {
            orgName = org.label;
            orgType = org.orgType.toString();
          }
        }

        tokenInfoModel.orgName = orgName;
        tokenInfoModel.orgType = orgType;
        const jwtToken: string = this.jwtService.sign(
          JSON.parse(JSON.stringify(tokenInfoModel)),
          {
            header: {
              typ: 'JWT',
              alg: 'HS256',
            },
            expiresIn: jwtConstants.expiresSecond,
            issuer: jwtConstants.issuer,
            privateKey: Buffer.from(jwtConstants.secret, 'base64').toString(
              'ascii',
            ),
          },
        );

        const tokenModel: TokenModel = new TokenModel();
        tokenModel.token = jwtToken;

        loginLogEntity.loginStatus = '0';
        this.loginLogService.saveLoginLog(loginLogEntity);
        return this.resultData(tokenModel, 200, '登录成功！');
      } else {
        loginLogEntity.loginStatus = '1';
        this.loginLogService.saveLoginLog(loginLogEntity);
        return this.resultData(null, 300, '用户名密码不正确！');
      }
    } else {
      loginLogEntity.loginStatus = '1';
      this.loginLogService.saveLoginLog(loginLogEntity);
      return this.resultData(null, 300, '您输入的用户账号不存在！');
    }
  }
}
